package com.zh.mycommon.viewdata;

import org.jetbrains.annotations.Nullable;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 下拉框选项值
 *
 * @author ZH
 */
public final class SelectOption implements Serializable {
    /**
     * 节点名称
     */
    private String label;

    /**
     * 节点ID
     */
    private String value;

    /**
     * 子节点
     */
    private List<SelectOption> children;

    public SelectOption() {
    }

    public SelectOption(String label, String value) {
        this.label = label;
        this.value = value;
    }

    @SuppressWarnings("unchecked")
    public <V> SelectOption(TreeData<?> element, Function<V, String> labelFun) {
        this(labelFun.apply((V) element), element.getId().toString());

        var children = element.getChildren();
        if (children != null) {
            this.children = children.stream()
                    .map(e -> new SelectOption(e, labelFun))
                    .collect(Collectors.toList());
        }
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    @Nullable
    public List<SelectOption> getChildren() {
        return children==null?null:Collections.unmodifiableList(children);
    }

    @Override
    public String toString() {
        String str = this.children == null ? "null" : "[... size=" + children.size() + "]";
        return "SelectOption{" +
                "label = " + label + ", " +
                "value = " + value + ", " +
                "children = " + str +
                "}";
    }

}
